<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------
namespace app\common\model;

use think\Validate;
use think\model\concern\SoftDelete;
use think\facade\Log;
use think\Db;


class Recharge extends Common
{
    protected $name = 'recharge';

    use SoftDelete;
    //时间自动存储
    protected $autoWriteTimestamp = true;
    protected $createTime = 'ctime';
    protected $updateTime = 'utime';
    //软删除位
    protected $deleteTime = 'isdel';

    const IS_PUB_YES = 1;   //发布
    const IS_PUB_NO = 2;    //暂不发布
  
    protected $rule =   [
        'name'              =>  'require|max:16',
        'money'             =>  'require|regex:/^[0-9]+(.[0-9]{1,2})?$/',
        'gift'              =>  'require|regex:/^[0-9]+(.[0-9]{1,2})?$/',
        'desc'              =>  'require|max:32',
        'sort'              =>  'number',
    ];
     
    protected $msg  =   [
        'name.require'              =>  '请输入规则名称',
        'name.max'                  =>  '规则名最多不能超过16个字符',
        'money'                     =>  '请输入一个合法的金额',
        'gift'                      =>  '请输入一个合法的赠送余额',
        'desc.require'              =>  '请输入规则描述',
        'desc.max'                  =>  '规则描述最多不能超过32个字符',
        'sort.number'               =>  '排序必须是数字类型',
    ];

    const RECHARGE_STATUS_YES = 1;      //启用
    const RECHARGE_STATUS_NO  = 2;      //禁用
    /**
     * @param $post
     *
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if (isset($post['limit'])) {
            $limit = $post['limit'];
        } else {
            $limit = config('paginate.list_rows');
        }

        $tableWhere = $this->tableWhere($post);
        $list = $this->field($tableWhere['field'])->where($tableWhere['where'])->order($tableWhere['order'])->paginate($limit);
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型
        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;
        return $re;
    }

    /**
     *  添加规则方法
     * User:tony
     * @param $data
     * @return array
     */
    public function addData($data)
    {
        $validate = new Validate($this->rule, $this->msg);
        $result = ['status' => true, 'msg' => '保存成功', 'data' => ''];

        if (!$validate->check($data)) {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        } else {
            if($data['expires_in'] == '') {
                $data['expires_in'] = '';
            } else { 
                $data['expires_in'] = strtotime($data['expires_in']." 23:59:59");
            }

            // 判断是否存在相同的充值规则
            $recharge_info = $this->where(['money'=>$data['money'], 'gift'=>$data['gift'], 'expires_in'=>$data['expires_in']])->find();
            if($recharge_info){
                $result['status'] = false;
                $result['msg'] = '存在充值金额、赠送金额、失效时间相同的充值规则';   
                
            } else {
                if (!$this->allowField(true)->save($data)) {
                    $result['status'] = false;
                    $result['msg'] = '保存失败';    
                }
            }
        }

        return $result;
    }

    /**
     *  修改规则信息
     * User:tony
     * @param $data
     * @return array
     */
    public function saveData($data)
    {
        $validate = new Validate($this->rule,$this->msg);
        $result = ['status' => true, 'msg' => '保存成功' , 'data' => ''];
        if(!$validate->check($data))
        {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        } else {
            if($data['expires_in'] == '') {
                $data['expires_in'] = '';
            } else { 
                $data['expires_in'] = strtotime($data['expires_in']." 23:59:59");
            }
            
            // 判断是否存在相同的充值规则
            $recharge_info = $this->where(['money'=>$data['money'], 'gift'=>$data['gift'], 'expires_in'=>$data['expires_in']])->where('id','neq',$data['id'])->find();
            if($recharge_info){
                $result['status'] = false;
                $result['msg'] = '存在充值金额、赠送金额、失效时间相同的充值规则';   
                
            } else {
                if (!$this->allowField(true)->save($data, ['id'=>$data['id']])) {
                    $result['status'] = false;
                    $result['msg'] = '保存失败';
                }
            }
        }
        return $result;
    }

    /**
     *  取充值规则信息
     * User:tony
     * @param $data
     * @return array
     */
    public function getRechargeList()
    {
        $result = ['status' => true, 'msg' => '查询成功' , 'data' => ''];
        $sqlQuery = "select `id`, `name`, `money`, `gift`, `desc` From zl_recharge where is_pub = 1 and (expires_in > " . time() . " or expires_in = 0 )";
        $listQuery = Db::connect()->query($sqlQuery);

        $result['data'] = $listQuery;
        return $result;
    }

    /**
     *  根据ID取充值规则信息
     * User:tony
     * @param $data
     * @return array
     */
    public function getRechargeById($id)
    {
        $result = ['status' => true, 'msg' => '查询成功' , 'data' => '']; 
        $sqlQuery = "select `id`, `name`, `money`, `gift`, `desc` From zl_recharge where id = '".$id."' and is_pub = 1 and (expires_in > " . time() . " or expires_in = 0 )";
        $listQuery = Db::query($sqlQuery);
 
        if (!$listQuery || count($listQuery) == 0) {
            $result['status'] = false;
        }
 
        $result['data'] = $listQuery[0];
        return $result;
    }

    /**
     *  table WHERE搜索
     * User:tony
     * @param $post
     * @return mixed
     */
    protected function tableWhere($post)
    {
        $where = [];
        if (isset($post['name']) && $post['name'] != "") {
            $where[] = ['name', 'like', '%' . $post['name'] . '%'];
        }
        if (isset($post['expires_in']) && $post['expires_in'] != "") {
            $date_array = explode('到', $post['expires_in']);
            $sexpires_in = strtotime($date_array[0] . '00:00:00', time());
            $eexpires_in = strtotime($date_array[1] . '23:59:59', time());
            $where[] = ['expires_in', ['EGT', $sexpires_in], ['ELT', $eexpires_in], 'and'];
        }
        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = ['sort ASC'];
        return $result;
    }

    protected function tableFormat($list)
    {
        foreach ($list as $key => $val) {
            $list[$key]['ctime'] = date('Y-m-d H:i:s', $val['ctime']);
            $list[$key]['utime'] = date('Y-m-d H:i:s', $val['utime']);

            if($val['expires_in'] == '') {
                $list[$key]['expires_in'] = '长期有效';
            } else {
                $list[$key]['expires_in'] = date('Y-m-d', $val['expires_in']);
            }
        }
 
        return $list;
    } 
    
    /**
     *
     * 快捷更改状态
     * @param $id
     * @param $status
     * @return array
     */
    public function changeStatus($id,$is_pub)
    {
        $result = ['status'=>true,'msg'=>'','data'=>''];
        $where['id'] = $id;

        switch($is_pub)
        {
            case 'true':
                $this->save(['is_pub'=>self::RECHARGE_STATUS_YES],$where);
                $result['msg'] = '已'.config('params.payments')['status'][self::RECHARGE_STATUS_YES];
                break;
            case 'false':
                $this->save(['is_pub'=>self::RECHARGE_STATUS_NO],$where);
                $result['msg'] = '已'.config('params.payments')['status'][self::RECHARGE_STATUS_NO];
                break;
            default:
                $result['status'] = false;
                $result['msg'] = '非法操作';
                break;
        }

        return $result;
    }

}
